<?php
/**
 * Created by PhpStorm.
 * User: MrHung
 * Date: 7/1/14
 * Time: 6:08 PM
 */
session_start();
error_reporting(0);

/*
       * --------------------------
       *   Require/Include Files
       * -------------------------
       */
require_once('../../class_ajax_request/classAjax.php');
include_once('../../application/functions.php');
include_once('../../application/DataConfig.php');
require_once'../../vendor/facebook/facebook.php';
$obj = new AjaxRequest();
$rs = $obj->getSetting();

$app_id = $rs[0]['FB_APP_ID'];
$secret = $rs[0]['FB_APP_SECRET'];
$facebook = new Facebook(array(
    'appId'=>$app_id,
    'secret'=>$secret,
    'cookie'=>true
));

$user = $facebook->getUser();

$accessToken = $facebook->getAccessToken();
if ($user) {
    try {

        $user_profile = $facebook->api('/me');
        if($user_profile['email'] == ''){
            die('Cannot fetch Your email from FaceBook!, Please Confirm Your email on Facebook');
        }
//        $result = $facebook->api(
//            '/me/feed/',
//            'post',
//            array('message' => 'Playing around with FB Graph..')                     N
//        );
        $_SESSION['ffb'] = true;

      $findUser =  $obj->findUserByEmail($user_profile['email']);
     //print_r($user_profile);die;
     if(count($findUser) == 0){

         //insert user into db , login  and redirect
         $fb_picture = "https://graph.facebook.com/".$user_profile['id']."/picture";
         $user_save = array(
            // 'username'=> alphabetconvert($user_profile['first_name']),
             'name' => $user_profile['first_name'].' '.$user_profile['last_name'],
             'email' => $user_profile['email'],
             'avatar' => $fb_picture,
             'status'=>'active',
             'type_account'=>1,
             'language'=>'en',
             'mode' => 1,
             'sex'=> $user_profile['gender'],
             'birth' => isset($user_profile['birthday'])? strtotime($user_profile['birthday']) : '0'
         );
      //  $userIdAfterInsert = $obj->signUpWithFb($user_save);
        // login
         $_SESSION['fb_redirect'] = true;
         $_SESSION['fbLoginData'] = $user_save;
       //  $_SESSION['username']      = $user_save['username'];
       //  $_SESSION['authenticated'] = $userIdAfterInsert;
       //  $_SESSION['lang_user']     = $user_save['language'];
         header("Location: ".URL_BASE.'/user/changeuser');
     }else{
         // login and redirect to homepage
//        echo '<pre>';
//         print_r($findUser);
//         echo '</pre>';
         if($findUser[0]['status'] == 'active'){
             $_SESSION['username']      = $user_save['username'];
             $_SESSION['authenticated'] = $findUser[0]['id'];
             $_SESSION['lang_user']     = $user_save['language'];
             header("Location: ".URL_BASE);
         }else{
             header("Location: ".URL_BASE);
         }


     }


    }
    catch (Exception $e) {
        echo $e->getMessage();
        exit();
    }
}else{
    echo 'Wrong FB_APP_ID OR FB_SECRET';exit;
}

 function alphabetconvert($phrase, $maxLength = 100000000000000)
{
    $from = array('À', 'Á', 'Ả', 'Ã', 'Ạ', 'Ă', 'Ằ', 'Ắ', 'Ẳ', 'Ẵ', 'Ặ', 'Â', 'Ầ', 'Ấ', 'Ẩ', 'Ẫ', 'Ậ',
        'à', 'á', 'ả', 'ã', 'ạ', 'â', 'ầ', 'ấ', 'ẩ', 'ẫ', 'ậ', 'ă', 'ằ', 'ắ', 'ẳ', 'ẵ', 'ặ',
        'Ò', 'Ó', 'Ỏ', 'Õ', 'Ọ', 'Ô', 'Ồ', 'Ố', 'Ổ', 'Ỗ', 'Ộ', 'Ơ', 'Ờ', 'Ớ', 'Ở', 'Ỡ', 'Ợ',
        'ò', 'ó', 'ỏ', 'õ', 'ọ', 'ô', 'ồ', 'ố', 'ổ', 'ỗ', 'ộ', 'ơ', 'ờ', 'ớ', 'ở', 'ỡ', 'ợ',
        'Ù', 'Ú', 'Ủ', 'Ũ', 'Ụ', 'Ư', 'Ừ', 'Ứ', 'Ử', 'Ữ', 'Ự',
        'ù', 'ú', 'ủ', 'ũ', 'ụ', 'ư', 'ừ', 'ứ', 'ử', 'ữ', 'ự',
        'È', 'É', 'Ẻ', 'Ẽ', 'Ẹ', 'Ê', 'Ề', 'Ế', 'Ể', 'Ễ', 'Ệ',
        'è', 'é', 'ẻ', 'ẽ', 'ẹ', 'ê', 'ề', 'ế', 'ể', 'ễ', 'ệ',
        'Ì', 'Í', 'Ỉ', 'Ĩ', 'Ị',
        'ì', 'í', 'ỉ', 'ị', 'ĩ',
        'Ỳ', 'Ý', 'Ỉ', 'Ỹ', 'Ỵ',
        'ỳ', 'ý', 'ỷ', 'ỵ', 'ỹ',
        '.','/','"\"','%'
    );

    $to = array('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
        'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a',
        'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O',
        'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o',
        'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U',
        'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u',
        'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E',
        'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e',
        'I', 'I', 'I', 'I', 'I',
        'i', 'i', 'i', 'i', 'i',
        'Y', 'Y', 'Y', 'Y', 'Y',
        'y', 'y', 'y', 'y', 'y',
        '_','_' ,'_','-'
    );


    $newstring = str_replace($from, $to, $phrase);

    $result = strtolower($newstring);

    $result = preg_replace("/[^A-Za-z0-9\s-._\/]/", "", $newstring);
    $result = trim(preg_replace("/[\s-]+/", " ", $newstring));
    $result = trim(substr($newstring, 0, $maxLength));
    $result = preg_replace("/\s/", "-", $newstring);

    return $result;

}